//
//  loadXMLViewController.m
//  i18n
//
//  Created by Myung Scott on 11. 11. 25..
//  Copyright (c) 2011년 patrick.decaluwe@student.uclouvain.be. All rights reserved.
//

#import "loadXMLViewController.h"

@implementation loadXMLViewController
@synthesize progressView;
@synthesize progressAlert;
@synthesize urlTextField;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

-(IBAction)homeButtonClicked:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}

-(IBAction)downloadButtonClicked:(id)sender
{
    [self getXMLFrom:urlTextField.text];
    
	NSLog(@"Download Started");
    
    self.progressAlert = [[UIAlertView alloc] initWithTitle:@"Please wait..."
                                                    message:@"파일 다운로드 중입니다" 
                                                   delegate:self cancelButtonTitle:nil 
                                          otherButtonTitles:nil];
    self.progressAlert.tag = 12;
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(30.0f, 80.0f, 225.0f, 90.0f)];
    [self.progressAlert addSubview:self.progressView];
    [self.progressView setProgressViewStyle:UIProgressViewStyleBar];
    [self.progressAlert show];
    [self.progressAlert release];
}

-(void)getXMLFrom:(NSString*)url {
	if( httpManager ) {
		[httpManager release];
		httpManager = nil;
	}
	httpManager = [[HttpManager alloc] initWithUrl:url delegate:self];
}

#pragma mark HttpManagerDelegate
-(void)connectionDidFinish:(HttpManager*)aHttpManager {
	receivedData = httpManager.receivedData;
    NSLog(@"Working"); 
    //NSLog([[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]);

    // save it into sandbox
    NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@", [dirArray objectAtIndex:0]);

    NSString *url = urlTextField.text;
    NSArray *parts = [url componentsSeparatedByString:@"/"];
    NSString *filename = [parts objectAtIndex:[parts count]-1];
    
//    NSLog(filename);

    NSString *path = [NSString stringWithFormat:@"%@/%@", [dirArray objectAtIndex:0], filename];
   
    if ([receivedData writeToFile:path options:NSAtomicWrite error:nil] == NO) {
        NSLog(@"writeToFile error");
    }
    else {
        NSLog(@"Written!");
        [self.progressAlert dismissWithClickedButtonIndex:0 animated:YES];
    }
}

-(void)connectionDidFail:(HttpManager*)aHttpManager {
    [self.progressAlert dismissWithClickedButtonIndex:0 animated:YES];
	UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"Fail" message:@"Couldn't connect" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] autorelease];
	[alertView show];
}

-(void)connectionDidReceiveResponse:(NSURLResponse *)response {
    NSDictionary *responseHeaderFields;
    
    // 받은 header들을 dictionary형태로 받고
    responseHeaderFields = [(NSHTTPURLResponse *)response allHeaderFields];	
	totalsize = [[responseHeaderFields objectForKey:@"Content-Length"] integerValue];
	NSLog(@"Header: %@", [responseHeaderFields objectForKey:@"Content-Length"]);
}

-(void)connectionDidReceiveData:(HttpManager*)aHttpManager {
	NSInteger currentLength = aHttpManager.receivedData.length;
    self.progressView.progress = (float)currentLength/(float)totalsize;	
	//NSLog(@"%i", aHttpManager.receivedData.length);
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
